﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Caliburn.Micro;
using F2S.LINQ2LinkedIn.Client.Events;
using F2S.LINQ2LinkedIn.Client.Services;

namespace F2S.LINQ2LinkedIn.Client.ViewModels
{
    public class MainViewModel : Conductor<object>, IHandle<AuthorizeSucceeded>
    {
        public string LinkedInNowSectionTitle { get; set; }

        private bool _loggedIn;

        public bool LoggedIn
        {
            get { return _loggedIn; }
            set
            {
                if (value != _loggedIn)
                {
                    _loggedIn = value;
                    NotifyOfPropertyChange(() => LoggedIn);
                }
            }
        }

        private ILinkedInService _linkedInService;
        private IEventAggregator _eventAggregator;

        public MainViewModel(ILinkedInService linkedIn, IEventAggregator eventAggregator)
        {
            _linkedInService = linkedIn;
            _eventAggregator = eventAggregator;

            _eventAggregator.Subscribe(this);
        }

        protected override void OnActivate()
        {
            base.OnActivate();
        }

        protected override void OnDeactivate(bool close)
        {
            base.OnDeactivate(close);
        }

        async protected override void OnInitialize()
        {
            base.OnInitialize();

            ActivateItem(new InitializingViewModel(_linkedInService));

            var result = await _linkedInService.Initialize();
            if (result.RequiresAuthorization) ActivateItem(IoC.Get<RequiresAuthorizationViewModel>());
            else if (_linkedInService.IsLoggedIn) ActivateItem(IoC.Get<MasterViewModel>());
        }

        void _linkedIn_StatusEvent(object sender, StatusEvent e)
        {
            switch (e.Code)
            {
                case StatusEventCode.Initializing:
                    ActivateItem(new InitializingViewModel(_linkedInService));
                    break;

                case StatusEventCode.Initialized:
                    if (_linkedInService.RequiresAuthorization)
                    {
                        ActivateItem(IoC.Get<RequiresAuthorizationViewModel>());
                    }
                    break;
            }
        }

        public void Handle(AuthorizeSucceeded message)
        {
            ActivateItem(IoC.Get<MasterViewModel>());
        }
    }
}
